<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Moneytx extends Backend
{

    /**
     * Moneytx模型对象
     * @var \app\admin\model\Moneytx
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Moneytx;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','money','createtime','status']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function del($ids= null)
    {
        $ids=$this->request->param('ids');

        $info=Db::name('user_money_tx')->where('id',$ids)
            ->find();


        if($info['status']==1){
            $this->error('该记录已处理，请勿重复处理！');
        }


        addmymoney($info['user_id'],$info['money'],'提现驳回');

        Db::name('user_money_tx')->where('id',$ids)
            ->delete();


        $this->success();

    }
    //提现
    public function tx(){


        $ids=$this->request->param('ids');
        $info=Db::name('user_money_tx')->where('id',$ids)
            ->find();


        if($info['status']==1){

          $this->error('该记录已处理，请勿重复处理！');
        }



        $info=Db::name('user_money_tx')->where('id',$ids)
            ->find();

        $user=Db::name('unishop_user_extend')->where('user_id',$info['user_id'])
            ->order('id  desc')
            ->find();



        $money = intval($info['money']*100);

        $appid='wxc54a4da93113e17c';
        $openid=$user['openid'];
        $trade_no='tx'.date('YmdHis');


        $infos=[["info_type"=>"岗位类型", "info_content"=>"推广员"],["info_type"=>"报酬说明", "info_content"=>"佣金返利"]];
        $post_data = [
            "appid" => $appid,//appid
            "out_bill_no"=>$trade_no,
            "transfer_scene_id"=>'1005',
            "openid" => $openid,
            "transfer_amount"=>$money,
            "transfer_remark"=>'佣金报酬',
            "transfer_scene_report_infos" => $infos,
        ];
        $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills';
        //JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE  防止中文被转义
        $result = $this->wx_post($url, json_encode($post_data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));

        $result = json_decode($result, true);

         if (isset($result['package_info'])) {

            Db::name('user_money_tx')->where(['id'=>$ids])->update(['status'=>1]);

            Db::name('user_wxmoney')
                ->insert([
                    'user_id'=>$info['user_id'],
                    'status'=>0,
                    'package_info'=>$result['package_info']
                ]);
             $this->success('提现成功！');
         }else{

             $this->error($result['message']);
         }


    }

    /**post请求
     * @param $url
     * @param $param
     * @return bool|string
     */
    private function wx_post($url, $param)
    {
        $authorization = $this->getV3Sign($url, "POST", $param);
        $curl = curl_init();
        $headers = [
            'Authorization:' . $authorization,
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($curl, CURLOPT_POST, true);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     * 微信提现V3签名
     * @param $url
     * @param $http_method
     * @param $body
     * @return string
     */
    private function getV3Sign($url, $http_method, $body)
    {
        $nonce = strtoupper($this->createNonceStr(32));
        $timestamp = time();
        $url_parts = parse_url($url);
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));

        $sslKeyPath = "./cert/apiclient_key.pem";
        $mchid='1676098779';


        $certPath='./cert/apiclient_cert.pem';
        $certContent = file_get_contents($certPath);
        $certData = openssl_x509_parse($certContent, true);
        $serial_n = $certData['serialNumberHex'];


        //拼接参数
        $message = $http_method . "\n" .
            $canonical_url . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $body . "\n";
        $private_key = $this->getPrivateKey($sslKeyPath);
        openssl_sign($message, $raw_sign, $private_key, 'sha256WithRSAEncryption');
        $sign   = base64_encode($raw_sign);
        $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%s",serial_no="%s",signature="%s"', $mchid, $nonce, $timestamp, $serial_n, $sign);
        return $token;
    }

    /**
     * 生成随机32位字符串
     * @param $length
     * @return string
     */
    public function createNonceStr($length = 16) { //生成随机16个字符的字符串
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 获取私钥
     * @param $filepath
     * @return false|resource
     */
    private function getPrivateKey($filepath = '')
    {

        $filepath = "./cert/apiclient_key.pem";

        return openssl_get_privatekey(file_get_contents($filepath));
    }



}
